//
//  ParseProfileXMLReader.m
//  cliqset
//
//  Created by David Hinson on 3/4/09.
//  Copyright 2009 Sumner Systems Management, Inc.. All rights reserved.
//

#import "ParseProfileXMLReader.h"
#import "Profile.h"

@implementation ParseProfileXMLReader

@synthesize contentOfCurrentProperty  = _contentOfCurrentProperty;
@synthesize currentProfileObject      = _currentProfileObject;

NSString *strProfile                  = @"Profile";
NSString *strProfileGivenName         = @"GivenName";
NSString *strProfileMiddleName        = @"MiddleName";
NSString *strProfileFamilyName        = @"FamilyName";
NSString *strProfileHonorificPrefix   = @"HonorificPrefix";
NSString *strProfileHonorificSuffix   = @"HonorificSuffix";
NSString *strProfileGender            = @"Gender";
NSString *strProfileBirthday          = @"Birthday";
NSString *strProfileLocality          = @"Locality";
NSString *strProfileRegion            = @"Region";
NSString *strProfileCountry           = @"Country";
NSString *strProfilePostCode          = @"PostCode";
NSString *strProfileMaritalStatus     = @"MaritalStatus";
NSString *strProfileSexualOrientation = @"SexualOrientation";
NSString *strProfileAvatarURL         = @"AvatarURL";
NSString *strProfilePoliticalViews    = @"PoliticalViews";
NSString *strProfileReligiousViews    = @"ReligiousViews";
NSString *strProfileAboutMe           = @"AboutMe";

-(id)init {
	[super init];
	
	return self;
}

-(void)resetVars {
	
	self.contentOfCurrentProperty = nil;
	
	//if (@selector(_currentProfileObject) && _currentProfileObject.basicProfile!=nil && self.currentProfileObject.basicProfile) {
	//	[self.currentProfileObject.basicProfile release];
	//	self.currentProfileObject.basicProfile = nil;
	//}
	
	if (@selector(_currentProfileObject) && _currentProfileObject!=nil && self.currentProfileObject) {
		[self.currentProfileObject release];
		self.currentProfileObject = nil;
	}
}

- (void)parserDidStartDocument:(NSXMLParser *)parser
{
	[self resetVars];
}

- (void)parseXMLFileAtData:(NSData *)data parseError:(NSError **)error
{	
    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
	
    // Set self as the delegate of the parser so that it will receive the parser delegate methods callbacks.
    [parser setDelegate:self];
	
    // Depending on the XML document you're parsing, you may want to enable these features of NSXMLParser.
    [parser setShouldProcessNamespaces:NO];
    [parser setShouldReportNamespacePrefixes:NO];
    [parser setShouldResolveExternalEntities:NO];
    
    [parser parse];
    
    NSError *parseError = [parser parserError];
    if (parseError && error) {
        *error = parseError;
    }
	
	[self resetVars];
    
    [parser release];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if (qName) {
        elementName = qName;
    }
	
	if ([elementName isEqualToString:strProfile]) {		
		
		[self resetVars];
		
		self.currentProfileObject               = [[Profile alloc] init];
		//self.currentProfileObject.basicProfile  = [[BasicProfile alloc] init];
		
	} else if ([elementName isEqualToString:strProfileGivenName]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strProfileMiddleName]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strProfileFamilyName]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strProfileHonorificPrefix]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strProfileHonorificSuffix]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strProfileGender]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strProfileBirthday]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strProfileLocality]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strProfileRegion]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strProfileCountry]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strProfilePostCode]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strProfileMaritalStatus]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strProfileSexualOrientation]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strProfileAvatarURL]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strProfilePoliticalViews]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strProfileReligiousViews]) {
        self.contentOfCurrentProperty = [NSMutableString string];
	} else if ([elementName isEqualToString:strProfileAboutMe]) {
        self.contentOfCurrentProperty = [NSMutableString string];
    } else {
        // The element isn't one that we care about, so set the property that holds the 
        // character content of the current element to nil. That way, in the parser:foundCharacters:
        // callback, the string that the parser reports will be ignored.
        self.contentOfCurrentProperty = nil;
	}
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{     
	NSMutableData *imageData;
	NSString *imageURL;
	NSURL *url;
	NSMutableURLRequest* request;
	NSURLResponse* response;
	NSError* error;
	
    if (qName) {
        elementName = qName;
    }
		
	// Given Name
    if ([elementName isEqualToString:strProfileGivenName]) {
		if (self.contentOfCurrentProperty) {
			self.currentProfileObject.basicProfile.givenName = self.contentOfCurrentProperty;
		} else {
			self.currentProfileObject.basicProfile.givenName = (NSMutableString*)@"";
		}
	}
	
	// Middle Name
    if ([elementName isEqualToString:strProfileMiddleName]) {
		if (self.contentOfCurrentProperty) {
			self.currentProfileObject.basicProfile.middleName = self.contentOfCurrentProperty;
		} else {
			self.currentProfileObject.basicProfile.middleName = (NSMutableString*)@"";
		}
	}
	
	// Family Name
    if ([elementName isEqualToString:strProfileFamilyName]) {
		if (self.contentOfCurrentProperty) {
			self.currentProfileObject.basicProfile.familyName = self.contentOfCurrentProperty;
		} else {
			self.currentProfileObject.basicProfile.familyName = (NSMutableString*)@"";
		}
	}
	
	// Honorific Prefix
    if ([elementName isEqualToString:strProfileHonorificPrefix]) {
		if (self.contentOfCurrentProperty) {
			self.currentProfileObject.basicProfile.honorificPrefix = self.contentOfCurrentProperty;
		} else {
			self.currentProfileObject.basicProfile.honorificPrefix = (NSMutableString*)@"";
		}
	}
	
	// Honorific Suffix
    if ([elementName isEqualToString:strProfileHonorificSuffix]) {
		if (self.contentOfCurrentProperty) {
			self.currentProfileObject.basicProfile.honorificSuffix = self.contentOfCurrentProperty;
		} else {
			self.currentProfileObject.basicProfile.honorificSuffix = (NSMutableString*)@"";
		}
	}
	
	// Gender
    if ([elementName isEqualToString:strProfileGender]) {
		if (self.contentOfCurrentProperty) {
			self.currentProfileObject.basicProfile.gender = self.contentOfCurrentProperty;
		} else {
			self.currentProfileObject.basicProfile.gender = (NSMutableString*)@"";
		}
	}
	
	// Birthday
    if ([elementName isEqualToString:strProfileBirthday]) {
		if (self.contentOfCurrentProperty) {
			self.currentProfileObject.basicProfile.birthdate = self.contentOfCurrentProperty;
		} else {
			self.currentProfileObject.basicProfile.birthdate = (NSMutableString*)@"";
		}
	}
	
	// Locality
    if ([elementName isEqualToString:strProfileLocality]) {
		if (self.contentOfCurrentProperty) {
			self.currentProfileObject.basicProfile.locality = self.contentOfCurrentProperty;
		} else {
			self.currentProfileObject.basicProfile.locality = (NSMutableString*)@"";
		}
	}
	
	// Region
    if ([elementName isEqualToString:strProfileRegion]) {
		if (self.contentOfCurrentProperty) {
			self.currentProfileObject.basicProfile.region = self.contentOfCurrentProperty;
		} else {
			self.currentProfileObject.basicProfile.region = (NSMutableString*)@"";
		}
	}
	
	// Country
    if ([elementName isEqualToString:strProfileCountry]) {
		if (self.contentOfCurrentProperty) {
			self.currentProfileObject.basicProfile.country = self.contentOfCurrentProperty;
		} else {
			self.currentProfileObject.basicProfile.country = (NSMutableString*)@"";
		}
	}
	
	// Post Code
    if ([elementName isEqualToString:strProfilePostCode]) {
		if (self.contentOfCurrentProperty) {
			self.currentProfileObject.basicProfile.postCode = self.contentOfCurrentProperty;
		} else {
			self.currentProfileObject.basicProfile.postCode = (NSMutableString*)@"";
		}
	}
	
	// Marital Status
    if ([elementName isEqualToString:strProfileMaritalStatus]) {
		if (self.contentOfCurrentProperty) {
			self.currentProfileObject.basicProfile.maritalStatus = self.contentOfCurrentProperty;
		} else {
			self.currentProfileObject.basicProfile.maritalStatus = (NSMutableString*)@"";
		}
	}
	
	// Sexual Orientation
    if ([elementName isEqualToString:strProfileSexualOrientation]) {
		if (self.contentOfCurrentProperty) {
			self.currentProfileObject.basicProfile.sexualOrientation = self.contentOfCurrentProperty;
		} else {
			self.currentProfileObject.basicProfile.sexualOrientation = (NSMutableString*)@"";
		}
	}
	
	// Avatar URL
    if ([elementName isEqualToString:strProfileAvatarURL]) {
		if (self.contentOfCurrentProperty) {
			self.currentProfileObject.basicProfile.avatarURL = self.contentOfCurrentProperty;
			imageURL        = self.contentOfCurrentProperty;
			
			// NSLog(@"Avatar URL: %@", imageURL);
			
			url             = [NSURL URLWithString:imageURL];
			request         = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0];
			
			imageData       = (NSMutableData*)[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
			self.currentProfileObject.basicProfile.avatarBlob = (NSMutableData*)imageData;
		} else {
			self.currentProfileObject.basicProfile.avatarURL = (NSMutableString*)@"";
		}
	}
	
	// Political Views
    if ([elementName isEqualToString:strProfilePoliticalViews]) {
		if (self.contentOfCurrentProperty) {
			self.currentProfileObject.basicProfile.politicalViews = self.contentOfCurrentProperty;
		} else {
			self.currentProfileObject.basicProfile.politicalViews = (NSMutableString*)@"";
		}
	}
	
	// Religious Views
    if ([elementName isEqualToString:strProfileReligiousViews]) {
		if (self.contentOfCurrentProperty) {
			self.currentProfileObject.basicProfile.religiousViews = self.contentOfCurrentProperty;
		} else {
			self.currentProfileObject.basicProfile.religiousViews = (NSMutableString*)@"";
		}
	}
	
	// About Me
    if ([elementName isEqualToString:strProfileAboutMe]) {
		if (self.contentOfCurrentProperty) {
			self.currentProfileObject.basicProfile.aboutMe = self.contentOfCurrentProperty;
		} else {
			self.currentProfileObject.basicProfile.aboutMe = (NSMutableString*)@"";
		}
	}
	
	if ([elementName isEqualToString:strProfile]) {
		// we will write the Status to an array here...
		if (self.currentProfileObject) {
			[(id)[[UIApplication sharedApplication] delegate] performSelectorOnMainThread:@selector(addProfile:) withObject:self.currentProfileObject waitUntilDone:YES];
		}
	}
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (self.contentOfCurrentProperty) {
        // If the current element is one whose content we care about, append 'string'
        // to the property that holds the content of the current element.
		if (string) {
			string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
			string = [string stringByReplacingOccurrencesOfString:@"\r" withString:@""];
			string = [string stringByReplacingOccurrencesOfString:@"\n" withString:@""];
			[self.contentOfCurrentProperty appendString:string];
		}
    }
}

-(void) dealloc {
	[_contentOfCurrentProperty release];
	[_currentProfileObject release];	
	[super dealloc];
}

@end
